package com.cbn.ibcp.web.smp.utils;

import com.cbn.ibcp.common.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.HibernateValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;

/**
 * 数据校验帮助类
 */
public class ValidatorUtil {

    private static final Logger log = LoggerFactory.getLogger(ValidatorUtil.class);

    private static Validator validator = Validation.byProvider(HibernateValidator.class).configure()
            .failFast(true).buildValidatorFactory().getValidator();

    /**
     * 实体校验
     *
     * @param obj
     * @throws BusinessException
     */
    public static <T> void validate(T obj) throws BusinessException {
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj, new Class[0]);
        if (!constraintViolations.isEmpty()) {
            ConstraintViolation<T> validateInfo = (ConstraintViolation<T>) constraintViolations.iterator().next();
            // validateInfo.getMessage() 校验不通过时的信息，即message对应的值
            log.error(validateInfo.getMessage());
            throw new BusinessException(validateInfo.getMessage());
        }
    }

    /**
     * 校验数组是否不为空，并且选择是否抛出异常信息
     * @param list
     * @param continueProcess
     */
    public static boolean isNotEmptyList(List list, boolean continueProcess, String customMessage) {
        String errorMsg = StringUtils.isBlank(customMessage) ? "参数数组为空" : customMessage;
        if (CollectionUtils.isEmpty(list)) {
            log.error(errorMsg);
            if (!continueProcess) {
                throw new BusinessException(errorMsg);
            }
            return false;
        }
        return true;
    }

    /**
     * 分组校验
     * @param validateDatas
     * @param validateGroup
     * @param <T>
     */
    public static <T> void validateParams(List<T> validateDatas, Class ... validateGroup){
        if(CollectionUtils.isEmpty(validateDatas)){
            throw new BusinessException("校验参数为空");
        }
        for (T validateData : validateDatas) {
            validateParam(validateData,validateGroup);
        }
    }

    public static <T> void validateParam(T validateData, Class ... validateGroup){
        if(validateData == null){
            throw new BusinessException("校验参数为空");
        }
        //Validator validator = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
        Set<ConstraintViolation<T>> validate = validator.validate(validateData,validateGroup);
        for(ConstraintViolation<T> error : validate){
            log.error("validator参数校验不通过,报错信息:{}",error.getMessage());
            throw new BusinessException(error.getMessage());
        }
    }
}

